<!--云闪推——开头/片尾库——上传视频-->
<template>
<!--  需做限制，如果已有4个视频，那么只能再上传1个视频 -->
  <ele-modal
    width="460px"
    :visible="visible"
    :append-to-body="true"
    :close-on-click-modal="true"
    custom-class="ele-dialog-form"
    title="上传文件"
    limit="30"
    @update:visible="updateVisible"
  >
    <!--判断视频最大上传个数为5-->
    <el-upload
      ref="upload"
      :disabled="loading == true?true:false"
      :file-list="fileList"
      :on-exceed="handleExceed"
      :on-change="onUpload"
      :auto-upload="false"
      :limit="5"
      accept=".mp4,.3gp,.mov"
      class="upload-demo"
      drag
      :action="ossUrl"
      multiple>
      <i class="el-icon-upload" v-show="loading == false"></i>
      <el-image v-show="loading == true" style="width: 67px;    margin: 40px 0 16px;
    line-height: 50px;" :src="require('/src/assets/loading.gif')"></el-image>
      <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
      <div class="el-upload__tip" slot="tip">只能上传.mp4,.3gp,.mov文件，且不超过30M(视频单次上传最多5个)</div>
    </el-upload>
    <template v-slot:footer>
      <el-button
        size="small"
        @click="updateVisible(false)"
      >
        取消上传
      </el-button>
      <el-button
        :loading="loading"
        size="small"
        type="primary"
        @click.stop="selectVideo()"
      >
        开始上传
      </el-button>
    </template>
  </ele-modal>
</template>

<script>
  import {registerMedia, userOssSignature} from "@/api/creatCenter/material";
  import {getToken} from "@/utils/token-util";
  import axios from "axios";

  export default {
        name: "file-upload",
      props: {
        // 弹窗是否打开
        visible: Boolean,
      },
      data() {
        return {
          ossUrl:localStorage.getItem('ossUrl')?localStorage.getItem('ossUrl'):'', //上传图片action
          loading:false,
          fileList:[],
          data:{},
          isFile:false,
          // 用于判断，是否上传到最后一个
          isNum:0
        };
      },
      created() {
      },
      methods: {
        async selectVideo(){
          this.isNum=0
          console.log("this.fileList.length",this.fileList.length)
          if(this.fileList.length < 1) {
            console.log("请选择文件后提交")
            this.$message.error('请选择文件后提交');
            return
          }
          let isLt = true
          for(let i=0;i<this.fileList.length;i++){
            // 判断是否小于2mb
            if(this.fileList[i].size / 1024 / 1024 > 30){
              isLt=false
            }
          }
          if (!isLt) {
            for(let i=0;i<this.fileList.length;i++){
              // 判断是否小于2mb
              if(this.fileList[i].size / 1024 / 1024 > 30){
                this.fileList.splice(i,1)
              }
            }
            this.$message.error("请上传小于30MB文件");
            return
          }
          this.isFile=true
          this.$refs.upload.submit();  // 图片上传进度(修改隐藏)
          this.data = await userOssSignature()
          console.log('this.fileList.length',this.fileList.length)

          this.loading=true
          for(let i=0;i<this.fileList.length;i++) {
            console.log('this.fileList.length22222222', this.fileList.length)
            let file = this.fileList[i].raw
            console.log("file", file, 'file.name', file.name)
            let filename = file.name;
            let markIndex = (filename).lastIndexOf('.');
            let suffix = filename.substring(markIndex)
            let name=filename.substring(0,markIndex); // 截取除 .png前的字段名
            console.log('markIndex,suffix',markIndex,suffix)
            let date = new Date().getTime();
            // 构建请求参数
            let param = new FormData()
            param.append("key", this.data.dir + name+'.'+date + suffix)
            param.append("policy", this.data.policy)
            param.append("OSSAccessKeyId", this.data.accessId)
            param.append("success_action_status", '200')
            // param.append("callback",  this.data.callback)     //回调（not)
            param.append("signature", this.data.signature)
            param.append("file", file, file.name)
            param.append('success_action_status', '200')
            let config = {
              headers: {
                'Access-Control-Allow-Origin': '*',
                'x-oss-callback-Authorization': getToken()
              }
            }
            axios.post(this.data.host, param, config).then(res => {
              if (res.status == 200) {
                // 修改
                // this.$refs.upload.submit();  // 图片上传进度
                console.log('this.data.host', this.data.host + '/' + name+'.'+ date + suffix)
                let url = this.data.host + '/' + name+'.' + date + suffix;
                let type = file.type;
                console.log('进入上传file.type=====', file.type)
                // this.fileList=[]
                this.registerMedias(url, type);
              } else {
                this.loading = false
                this.$message.error('上传失败');
              }

            }).catch(err => {
              console.log(err)
            })
          }
        },

        registerMedias(url,type) {
          registerMedia({
            mediaUrl:url,//上传阿里云生成的地址
            mediaType:type,//文件类型
            username:this.$store.state.user.info.username,
            folderId:this.parentId
          })
            .then((data) => {
              this.isNum++
              console.log("this.isNum",this.isNum,'this.fileList.length',this.fileList.length)
              // setTimeout(()=>{
              if(this.fileList.length == this.isNum){  // (修改隐藏)
                this.$message.success('上传成功');
                this.loading=false
                //关闭弹窗
                this.updateVisible(false);
                // 清空已上传的文件列表（该方法不支持在 before-upload 中调用）
                this.$refs['upload'].clearFiles()
                this.onDone();
              }
              // },500)
            })
            .catch((e) => {
              this.loading=false
              this.$message.error(e.message);
            });
        },
        /* 更新 visible */
        updateVisible(value) {
          this.loading=false
          // 除了上传时，为了避免重复调用push_fileList,所以在上传时标识isFile为true，return_push
          this.isFile=false
          this.fileList=[]
          this.$emit('update:visible', value);
        },
        //文件超出个数限制时的钩子
        handleExceed(files, fileList) {
          let maxNum = 5
          this.$message.warning(`当前限制选择 ${maxNum} 个文件，本次选择了 ${files.length} 个文件`);
        },
        /* 上传 */
        onUpload(file) {
          console.log("this.isFile",this.isFile)
          // 修改
          if(this.isFile==true){
            return
          }
          this.fileList.push(file)
          console.log('this.fileList',this.fileList)
        },

        /* 完成刷新列表数据 */
        onDone() {
          this.$emit('done');
        },
      }
    }
</script>

<style scoped>

  /deep/ .el-upload-dragger{
    width: 420px !important;
  }

  /* 上传组件 —— 下load（加载中）图标样式 */
  /deep/ .el-upload-dragger .el-icon-loading{
    font-size: 67px;
    color: var(--color-text-placeholder);
    margin: 40px 0 16px;
    line-height: 50px;
  }
</style>
